var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var city = require("../../utils/city.js");
var app = getApp();
var isPosting = false;
const Upyun = require('../../utils/upyun-wxapp-sdk');
const upyun = new Upyun({
  bucket: 'artartimages',
  operator: 'upyunadmin2014',
  getSignatureUrl: 'https://api.artart.cn/api.php?ac=signupyun&publickey=' + util.publiccode
});
var oldData = '';
var isEdit = false;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    minHeight:0,
    typeIndex:0,
    // jj_topicType: [
    //   "艺术年表",
    //   "展览经历",
    //   "荣誉奖项",
    //   "收藏拍卖",
    //   "公益捐赠",
    //   "出版刊登"
    // ],
    jj_topicType:[
      { type: 13, name: "艺术年表" },
      { type: 8, name: "展览经历" },
      { type: 14, name: "荣誉奖项" },
      { type: 15, name: "收藏拍卖" },
      { type: 16, name: "公益捐赠" },
      { type: 18, name: "出版刊登" }
    ],
    selTopicType: { type: 13, name: "艺术年表" },
    
    citys: {},
    provinceLocation: [],
    provinceLocationIndex: 0,
    provinceId: [],
    cityLocation: [],
    cityLocationIndex: 0,
    cityId: [],
    areaLocation: [],
    areaLocationIndex: 0,
    areaId: [],
    province: [],
    city: [],
    area: [],
    provinceSel: 0,
    citySel: 0,
    areaSel: 0,

    uploadImg: [],
    token: "",
    uid: 0,
    imgWH: 0,
    titleValue: '',
    jigouValue: '',
    awardValue:'',
    plannerValue:'',
    addressValue: '',
    message: '',
    date: '',
    startDate: '',
    endDate: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    oldData = '';
    isEdit = false;
    var releaseType;
    if (options.data) {//有数据传过来，说明是编
      wx.showLoading({
        title: '加载中',
      })
      oldData = JSON.parse(options.data);
      isEdit = true;
      console.log("要编辑的数据：", oldData);
      releaseType = oldData.topictype;
    } else if(options.type) {
      releaseType = options.type;
    }
    
    if(releaseType){
      var index = 0;
      var topicType ='';
  
      if(releaseType == 8){
        index = 1;
        topicType = { type: 8, name: "展览经历" };
      } else if (releaseType == 14) {
        index = 2;
        topicType = { type: 14, name: "荣誉奖项" };
      } else if (releaseType == 15) {
        index = 3;
        topicType = { type: 15, name: "收藏拍卖" };
      } else if (releaseType == 16) {
        index = 4;
        topicType = { type: 16, name: "公益捐赠" };
      } else if (releaseType == 18) {
        index = 5;
        topicType = { type: 18, name: "出版刊登" };
      }
      if(topicType){
        this.setData({
          typeIndex: index,
          selTopicType: topicType
        });
      }
    }
    this.setTitle(this.data.selTopicType.name);

    var curDate = new Date();
    var curYear = curDate.getFullYear();
    var curDate_f = util.formatTime(curDate, '-', '');
    var startDate_f = util.formatTime(new Date(curYear - 50, 0, 1), '-', '');
    var endDate_f = util.formatTime(new Date(curYear + 49, 11, 31), '-', '');
    console.log("curDate_f = " + curDate_f + "; startDate_f = " + startDate_f + "; endDate_f = " + endDate_f);
    this.setData({
      date: curDate_f,
      startDate: startDate_f,
      endDate: endDate_f
    });
    this.load();
    var that = this;
    app.LoginUserInfo(function (res) {
      if (res && res != -1) {
        that.setData({
          uid: res.uid,
          token: res.token
        });
      }
    });

    //读取省市全部数据
    var citys = city.getCity();
    var province = [{ "title": "省", "areas": {} }];
    var provinceLocation = ["省"];
    var provinceId = [];
    for (var key in citys) {
      province = province.concat([citys[key]]);
      provinceLocation = provinceLocation.concat([citys[key].title]);
      provinceId = provinceId.concat([citys[key].area_id]);
    }
    console.log(province);
    this.setData({
      citys: citys,
      province: province,
      provinceLocation: provinceLocation,
      provinceId: provinceId
    });
    if(isEdit){
      var proId = oldData.provinceid;
      var proData = citys[proId]; 
      this.setCity(proData.areas);
    } else {
      this.setCity(province[0].areas);
    }
    
  },
  load: function () {
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          minHeight: res.windowHeight - 40,
          imgWH: (res.windowWidth - 18) / 4 - 12
        });
      }
    })
  },

  setTitle:function(title){
    wx.setNavigationBarTitle({
      title: title,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    if(isEdit){
      var photoArray = [];
      if (oldData.photos) {
        photoArray = oldData.photos.split(',');
      }
      this.setData({
        date: oldData.age,
        jigouValue: oldData.source,
        titleValue: oldData.topictitle,
        awardValue: oldData.award,
        plannerValue: oldData.planner,
        provinceSel: oldData.provinceid,
        citySel: oldData.cityid,
        areaSel: oldData.areaid,
        addressValue: oldData.address,
        message:oldData.message,
        uploadImg: photoArray
      });
      wx.hideLoading();
    }
  },
  
  //发布类型选择
  bindPickerSelType: function (e) {
    console.log("分类 下标序号：" + e.detail.value);
    var that = this;
    this.setData({
      typeIndex: e.detail.value,
      selTopicType: that.data.jj_topicType[e.detail.value]
    })
    that.setTitle(that.data.selTopicType.name);
  },
  //时间选择
  bindDateDate: function (e) {
    this.setData({
      date: e.detail.value
    })
  },

  releaseSubmit: function (e) {
    if (isPosting) {
      return false;
    }
    isPosting = true;
    var releaseType = this.data.selTopicType.type;

    var title = e.detail.value.title ? e.detail.value.title : '';//标题
    if (releaseType == 8 || releaseType == 14 || releaseType == 18) {
      if (!title || title.trim().length <= 0) {
        if (releaseType == 14){
          app.dialog('请输入活动', 'loading');
        } else {
          app.dialog('请输入名称', 'loading');
        }
        isPosting = false;
        return false;
      }
    }
    var date = this.data.date;
    if (!date || date.trim().length <= 0) {
      app.dialog('请选择时间', 'loading');
      isPosting = false;
      return false;
    }
    var jigou = e.detail.value.jigou ? e.detail.value.jigou : '';//机构
    if (releaseType == 15 || releaseType == 16) {
      if (!jigou || jigou.trim().length <= 0) {
        app.dialog('请输入机构', 'loading');
        isPosting = false;
        return false;
      }
    }
    var address = e.detail.value.address ? e.detail.value.address : '';//地点
    var planner = e.detail.value.planner ? e.detail.value.planner : '';//策展人
    var provinceId = e.detail.value.province ? e.detail.value.province : '';//省Id
    var cityId = e.detail.value.city ? e.detail.value.city : '';//市Id
    var areaId = e.detail.value.area ? e.detail.value.area : '';//区id
    var cityString = '';
    if (releaseType == 8) {
      if (!planner || planner.trim().length <= 0) {
        app.dialog('请输入策展人', 'loading');
        isPosting = false;
        return false;
      }
      if (!provinceId || !cityId || (this.data.areaLocation.length > 1 && !areaId)){
        app.dialog('请选择区域', 'loading');
        isPosting = false;
        return false;
      }
      if (!address || address.trim().length <= 0) {
        app.dialog('请输入地点', 'loading');
        isPosting = false;
        return false;
      }
      var cityString = this.data.provinceLocation[this.data.provinceLocationIndex] + " "
        + this.data.cityLocation[this.data.cityLocationIndex] + " ";
      if (this.data.areaLocationIndex > 0){
        cityString += this.data.areaLocation[this.data.areaLocationIndex];
      }
    }
    var award = e.detail.value.award ? e.detail.value.award : '';//奖项
    if (releaseType == 14) {
      if (!award || award.trim().length <= 0) {
        app.dialog('请输入奖项', 'loading');
        isPosting = false;
        return false;
      }
    }

    var message = e.detail.value.message;//message内容
    if (!message || message.trim().length <= 0) {
      var msgLabel = "事件内容";
      if (releaseType == 14 || releaseType == 15 || releaseType == 16) {
        msgLabel = "作品描述";
      } else if (releaseType == 18) {
        msgLabel = "介绍";
      } else if (releaseType == 8) {
        msgLabel = "展览内容";
      }
      app.dialog('请输入' + msgLabel, 'loading');
      isPosting = false;
      return false;
    }

    // wx.showLoading({ title: '发布中，请稍等' });
    wx.showLoading({ title: '发布中...' });
    //图片
    var photos = this.data.uploadImg;//选择的图片 	图片的本地文件路径列表
    var photos_param = "";
    if (photos && photos.length > 0) {
      if (photos.length == 0) {
        app.dialog('请上传图片', 'loading');
        isPosting = false;
        return false;
      }
      //data 里面是参数  我不知道是不是用这个接口  你看着改吧  再把内容和图片放里就好了
      var nowd = new Date();
      var nowm = nowd.getMonth() + 1;
      nowm = nowm.toString();
      if (parseInt(nowm) < 10) {
        nowm = '0' + nowm;
      }
      var nowda = nowd.getDate();
      nowda = nowda.toString();
      if (parseInt(nowda) < 10) {
        nowda = '0' + nowda;
      }
      var nowhour = nowd.getHours();
      nowhour = nowhour.toString();
      if (parseInt(nowhour) < 10) {
        nowhour = '0' + nowhour;
      }
      photos_param = photos.map(function (item) { return item.replace('wxfile://tmp_', util.imgHost + nowd.getFullYear().toString() + '/' + (nowm + nowda) + '/' + nowhour + '/') }).join(',');
    }

    var action = "posttopic";
    if (isEdit) {
      action = "edittopic";
    }
    var uid = this.data.uid;//用户id
    var token = this.data.token;//用户token
    var privatekey = utilMd5.hexMD5(uid + action + token);//私钥
    var data = {
      ac: action,
      topictype: releaseType,
      privatekey: privatekey,
      uid: uid,
      postuid: uid,
      topictitle: title,//标题
      provinceid: provinceId,//省Id
      cityid: cityId,//市Id
      areaid: areaId,//区id
      city: cityString, //城市
      address: address,//展览地址
      planner: planner,//策展人
      starttime: date,//展览时间
      age: date,//事件发生时间
      message: message,
      award: award,//奖项
      source: jigou,//机构
      xcx: 1,
      photos: photos_param
    }
    if (isEdit) {
      data.topicid = oldData.id;
    }
    console.log("简介-" + releaseType, data);

    util.api({
      data: data,
      method: "POST",
      success: function (responseData) {
        console.log(responseData);
        wx.hideLoading();
        if (responseData.data.id) {//你看是不是这个字段判断发布失败还是成功的
          isPosting = false;
          // wx.redirectTo({ url: "/pages/index/index?go=dongtai" });
          wx.reLaunch({ url: "/pages/index/index?go=dongtai" });
        } else {
          app.dialog('发布失败', 'loading');
          isPosting = false;
        }

      },
      fail: function (e) {
        isPosting = false;
        wx.hideLoading();
      }
    });
  },
  uploadImgs: function () {
    var that = this;
    var photos = this.data.uploadImg;
    if (photos.length >= 9) {
      app.dialog('最多上传9张图片', 'loading');
      return false;
    }

    wx.chooseImage({
      count: (9 - photos.length),
      sizeType: ['compressed'],
      sourceType: ['album'],
      success: function (res) {
        const tempFilePaths = res.tempFilePaths;
        wx.showLoading({ title: '图片上传中..', mask: 'true' });
        const tempFileCount = tempFilePaths.length;
        var uploadCount = 0;
        that.setData({
          uploadImg: tempFilePaths.concat(photos)
        })
        for (var photoi = 0; photoi < tempFileCount; photoi++) {
          var imageSrc = res.tempFilePaths[photoi]
          var nowd = new Date();
          var nowm = nowd.getMonth() + 1;
          nowm = nowm.toString();
          if (parseInt(nowm) < 10) {
            nowm = '0' + nowm;
          }
          var nowda = nowd.getDate();
          nowda = nowda.toString();
          if (parseInt(nowda) < 10) {
            nowda = '0' + nowda;
          }
          var nowhour = nowd.getHours();
          nowhour = nowhour.toString();
          if (parseInt(nowhour) < 10) {
            nowhour = '0' + nowhour;
          }
          var imgUrl = '/' + nowd.getFullYear().toString() + '/' + (nowm + nowda) + '/' + nowhour + '/' + imageSrc.split('_')[1]
          upyun.upload({
            localPath: imageSrc,
            remotePath: imgUrl,
            success: function (res) {
              uploadCount++;
              if (uploadCount == tempFileCount) {
                wx.showToast({
                  title: '上传成功',
                  icon: 'success',
                  duration: 1000
                })
              }
            },
            fail: function ({ errMsg }) {
              uploadCount++;
              if (uploadCount == tempFileCount) {
                wx.showToast({
                  title: '上传成功',
                  icon: 'success',
                  duration: 1000
                })
              }
              console.log('uploadImage fail, errMsg is', errMsg)
            }
          })
        }
        //wx.hideLoading();
      },
      fail: function ({ errMsg }) {
        console.log('chooseImage fail, err is', errMsg)
      }
    });
  },
  //删除图片
  deleteImg: function (e) {
    var index = e.currentTarget.dataset.index;
    var photos = this.data.uploadImg;
    photos.splice(index, 1);
    this.setData({
      uploadImg: photos
    });
  },

  setCity: function (areas) {
    var city = [{ "title": "市", "areas": {} }];
    var cityLocation = ["市"];
    var cityId = [];
    for (var key in areas) {
      city = city.concat([areas[key]]);
      cityLocation = cityLocation.concat([areas[key].title]);
      cityId = cityId.concat([areas[key].area_id])
    }
    this.setData({
      city: city,
      area: [],
      cityLocation: cityLocation,
      areaLocationIndex: 0,
      cityId: cityId
    });
    if(isEdit){
      this.setArea(this.data.citys[oldData.provinceid]['areas'][oldData.cityid].areas);
    } else {
      this.setArea(city[0].areas);
    }
    
  },
  setArea: function (areas) {
    var area = [{ "title": "区"}];
    var areaLocation = ["区"];
    var areaId = [];
    for (var key in areas) {
      area = area.concat([areas[key]]);
      areaLocation = areaLocation.concat([areas[key].title]);
      areaId = areaId.concat([areas[key].area_id])
    }
    
    this.setData({
      area: area,
      areaLocation: areaLocation,
      areaId: areaId
    });
  },

  bindPickerCityChange: function (e) {
    var name = e.currentTarget.dataset.name;
    if (name == "province") {
      this.setData({
        provinceLocationIndex: e.detail.value,
        cityLocation: [],
        cityLocationIndex: 0,
        citySel: 0,
        areaSel: 0
      });
      this.setCity(this.data.province[e.detail.value].areas);
    } else if (name == "city") {
      this.setData({
        cityLocationIndex: e.detail.value,
        areaLocation: [],
        areaLocationIndex: 0
      })
      this.setArea(this.data.city[e.detail.value].areas);
    } else if (name == "area") {
      this.setData({
        areaLocationIndex: e.detail.value
      })
    }
  },

  goAtherPage: function (e) {
    var url = e.currentTarget.dataset.link;
    wx.navigateTo({ url: url })
  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})